var GOAL_FINISHED = 1, GOAL_REWARD = 2;

exports.get = function(player, req, resp, onHandled) {
    do {
        player.getFightForce();
        var achievements = player.getAchievements();
        if (!achievements) {
            resp.code = 1; resp.desc = 'not open'; break;
        }

        resp.data.achievements = achievements;
    } while (false);

    onHandled();
}

exports.get_goal_reward = function(player, req, resp, onHandled) {
    do {
        if (isNaN(req.args.id)) {
            resp.code = 1; resp.desc = 'arg id invalid'; break;
        }
        var id = parseInt(req.args.id);

        var achievements = player.getAchievements();
        if (!achievements) {
            resp.code = 1; resp.desc = 'not open'; break;
        }

        var goal = achievements.goals[id];
        if (!goal) {
            resp.code = 1; resp.desc = 'id not exist'; break;
        }

        var goalConf = gConfAchieveGoal[id][goal.level];
        if (!goalConf) {
            resp.code = 1; resp.desc = 'got'; break;
        }

        if (goal.value < goalConf.GoalTarget) {
            resp.code = 1; resp.desc = 'not reach'; break;
        }

        achievements.score += goalConf.Score;
        var levelConf = gConfAchieveLevel[achievements.level];
        while (achievements.score >= levelConf.Score) {
            var nextLevelConf = gConfAchieveLevel[achievements.level + 1];
            if (nextLevelConf) {
                achievements.level += 1;
                achievements.score -= levelConf.Score;
                player.roleDirty = true;
                levelConf = nextLevelConf;
            } else {
                achievements.score = (levelConf.Score - 1);
                break;
            }
        }
        player.getFightForce();
        
        goal.level++;
        goal.value = 0;
        player.statAchievementGoal(id, goal);
        
        player.markDirty('achievements.level');
        player.markDirty('achievements.score');
        player.markDirty('achievements.goals.' +id);

        var achievementsUpdates = {};
        achievementsUpdates.level = achievements.level;
        achievementsUpdates.score = achievements.score;
        achievementsUpdates.goal = goal;

        var awards = [];
        for (var i = 1; i <= 2; ++i) {
            var award = goalConf['Award' + i];
            if (award) {
                awards.push(award);
            }
        }

        resp.data.awards = player.addAwards(awards);
        resp.data.score = goalConf.Score;
        resp.data.achievements_update = achievementsUpdates;
    } while (false);

    onHandled();
}
